package com.com.athengzhi.springCloud.controller;

import com.athengzhi.springCloud.entities.CommonResult;
import com.athengzhi.springCloud.entities.Payment;
import com.com.athengzhi.springCloud.lb.LoadBalanced;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @Package: com.com.athengzhi.springCloud.controller
 * @ClassName: OrderController
 * @Author: lhz
 * @CreateTime: 2023/4/18 10:56
 * @Description:
 */
@RestController
@Slf4j
public class OrderController {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Resource
    private LoadBalanced loadBalanced;

//    public static final String PAYMENT_URL = "http://localhost:8001";   单个集群的时候可以直接用这个
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
    //多个集群直接找服务名称，通过集群自动进行均衡调用，需要RestTemplet用@LoadBalanced注解

    @Resource
    private RestTemplate restTemplate;

//    使用restTemplet调用payment8001模块
    //用户操作支付模块的写操作
    @PostMapping("/consumer/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        //postForObject参数介绍：url，参数类型，返回结果
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }
    @GetMapping("/consumer/payment/getForEntity/{id}")
    public CommonResult getForEntityPayment(@PathVariable("id") Long id){
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/getForEntity/" + id, CommonResult.class);
        if(entity.getStatusCode().is2xxSuccessful()){  //2xx代表200等成功状态码，其余的类似
            return entity.getBody();   //获取响应体里面的body内容
        }else {
            return new CommonResult(444,"操作失败");
        }
    }

    @GetMapping(value = "/consumer/payment/getPort")
    public String getPaymentPort(){
        List<ServiceInstance> instances =discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() <= 0){
            return null;
        } 
        ServiceInstance instance = loadBalanced.instance(instances);
        URI uri = instance.getUri();
        return restTemplate.getForObject(uri+"/payment/getPort",String.class);
    }
}
